package com.zues.samples.dao.Impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import com.zues.samples.dao.BaseHibernateDAO;
import com.zues.samples.dao.TestDAO;
import com.zues.samples.model.PagerModel;
import com.zues.samples.model.Testmodel;
import com.zues.samples.service.modelVO.ExamTestOV;
import com.zues.samples.util.SystemContext;

@Repository
public class TestDAOImpl extends BaseHibernateDAO<Testmodel> implements TestDAO {

	/**
	 * 找全部考试题目
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Testmodel> findAllTest() throws Exception {
		String hql = "FROM Testmodel";
		List<Testmodel> testList = this.createQuery(hql).list();
		return testList;
	}

	/**
	 * 创建一个考试题目
	 */
	@Override
	public void createTest(Testmodel test) throws Exception {
		this.save(test);
	}

	/**
	 * 通过ID找到一个考试题目
	 */
	@Override
	public Testmodel getTestById(int testid) throws Exception {
		return this.get(testid);
	}

	/**
	 * 编辑题目
	 */
	@Override
	public void editTest(Testmodel test) throws Exception {
		if (test != null) {
			this.update(test);
		}
	}

	@Override
	public void deleteTest(int testid) throws Exception {
		Testmodel exsitTest = this.get(testid);
		if (exsitTest != null) {
			this.delete(exsitTest);
		}
	}

	/**
	 * 分页找考试题目
	 */
	@SuppressWarnings("unchecked")
	@Override
	public PagerModel<ExamTestOV> findAllByPage() {
		PagerModel<ExamTestOV> page = new PagerModel<ExamTestOV>();
		ArrayList<ExamTestOV> dates = new ArrayList<ExamTestOV>();

		int offset = SystemContext.getOffset();
		int pageSize = SystemContext.getSize();

		List<Testmodel> tempDates = this.createQuery("FROM Testmodel").setFirstResult(offset).setMaxResults(pageSize)
				.list();
		for (Testmodel testmodels : tempDates) {
			ExamTestOV examTestOV = new ExamTestOV();
			BeanUtils.copyProperties(testmodels, examTestOV);
			examTestOV.setSubName(testmodels.getSubject().getName());
			examTestOV.setTestType(testmodels.getExamTestType().getTestType());
			examTestOV.setTestScore(testmodels.getExamTestType().getTestTypeScore());
			dates.add(examTestOV);
		}
		page.setDates(dates);
		page.setOffset(offset);
		page.setPageSize(pageSize);

		// 获取总记录数
		long totalSize = (long) this.createQuery("select count(*) from Testmodel").uniqueResult();
		page.setTotalSize(totalSize);

		return page;
	}

}
